package com.sanri.tools.modules.mock.l7.websocket.chat.service;

import com.sanri.tools.modules.core.dtos.param.PageParam;
import com.sanri.tools.modules.core.security.UserService;
import com.sanri.tools.modules.mock.l7.websocket.chat.domain.ChatContact;
import com.sanri.tools.modules.mock.l7.websocket.chat.domain.ChatUser;
import com.sanri.tools.modules.mock.l7.websocket.chat.domain.Message;
import com.sanri.tools.modules.mock.l7.websocket.chat.repository.MessageRepository;
import com.sanri.tools.modules.mock.l7.websocket.chat.repository.ChatUserRepository;
import com.sanri.tools.modules.mock.l7.websocket.chat.service.ws.ChatSupport;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ChatService {

    @Autowired
    private ChatUserRepository chatUserRepository;

    @Autowired
    private MessageRepository messageRepository;

    @Autowired(required = false)
    private UserService userService;

    @Autowired
    private ChatSupport chatSupport;

    /**
     * 联系人列表
     * @return
     * @throws IOException
     */
    public List<ChatContact> contacts() throws IOException {
        List<ChatContact> chatContacts = new ArrayList<>();

        String username = userService.username();
        String[] listContacts = chatUserRepository.listContacts(username);
        if (ArrayUtils.isNotEmpty(listContacts)) {
            for (String contact : listContacts) {
                ChatUser chatUser = chatUserRepository.userSimpleInfo(contact);
                Message message = messageRepository.loadLastMessage(username, contact);
                ChatContact chatContact = new ChatContact(chatUser);
                chatContacts.add(chatContact);
                if (message != null) {
                    chatContact.setLastContent(message.getContent());
                    chatContact.setLastSendTime(message.getSendTime());
                }
            }
        }
        return chatContacts;
    }

    /**
     * 聊天消息列表
     * @param contact
     * @return
     */
    public List<Message> messages(String contact, PageParam pageParam) throws IOException {
        String username = userService.username();
        List<Message> messages = messageRepository.loadMessage(username, contact, -1, pageParam);
        return messages;
    }

    public void openChat() throws IOException {
        String username = userService.username();
        chatUserRepository.openChat(username);
    }

    public void sendMessage(Message message) throws IOException {
        message.setFromContactId(userService.username());
        chatSupport.sendMessage(message);
    }
}
